﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.IO;
using System.Security.Cryptography;
using System.Runtime.InteropServices;

namespace Common
{
    /// <summary>
    /// 工具类
    /// </summary>
    public class CommUtils
    {
        private static Regex RegexBr = new Regex(@"(\r\n)", RegexOptions.IgnoreCase);

        #region 缓存工具

        /// <summary>
        /// 清除页面缓存
        /// </summary>
        public static void NoCache()
        {
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Expires = 0;
            HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.AddHeader("pragma", "no-cache");
            HttpContext.Current.Response.AddHeader("cache-control", "private");
            HttpContext.Current.Response.CacheControl = "no-cache";
        }

        #endregion

        #region 字符串工具

        /// <summary>
        /// 返回字符串真实长度, 1个汉字长度为2
        /// </summary>
        /// <returns></returns>
        public static int GetStringLength(string str)
        {
            return Encoding.Default.GetBytes(str).Length;
        }

        /// <summary>
        /// 判断指定字符串在指定字符串数组中的位置
        /// </summary>
        /// <param name="strSearch">字符串</param>
        /// <param name="stringArray">字符串数组</param>
        /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
        /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>
        public static int GetInArrayID(string strSearch, string[] stringArray, bool caseInsensetive)
        {
            for (int i = 0; i < stringArray.Length; i++)
            {
                if (caseInsensetive)
                {
                    if (strSearch.ToLower() == stringArray[i].ToLower())
                    {
                        return i;
                    }
                }
                else
                {
                    if (strSearch == stringArray[i])
                    {
                        return i;
                    }
                }

            }
            return -1;
        }

        /// <summary>
        /// 判断指定字符串在指定字符串数组中的位置
        /// </summary>
        /// <param name="strSearch">字符串</param>
        /// <param name="stringArray">字符串数组</param>
        /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>		
        public static int GetInArrayID(string strSearch, string[] stringArray)
        {
            return GetInArrayID(strSearch, stringArray, true);
        }

        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="strSearch">字符串</param>
        /// <param name="stringArray">字符串数组</param>
        /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string strSearch, string[] stringArray, bool caseInsensetive)
        {
            return GetInArrayID(strSearch, stringArray, caseInsensetive) >= 0;
        }

        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="stringarray">字符串数组</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string str, string[] stringarray)
        {
            return InArray(str, stringarray, false);
        }

        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="stringarray">内部以逗号分割单词的字符串</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string str, string stringarray)
        {
            return InArray(str, SplitString(stringarray, ","), false);
        }

        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="stringarray">内部以逗号分割单词的字符串</param>
        /// <param name="strsplit">分割字符串</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string str, string stringarray, string strsplit)
        {
            return InArray(str, SplitString(stringarray, strsplit), false);
        }

        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="stringarray">内部以逗号分割单词的字符串</param>
        /// <param name="strsplit">分割字符串</param>
        /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string str, string stringarray, string strsplit, bool caseInsensetive)
        {
            return InArray(str, SplitString(stringarray, strsplit), caseInsensetive);
        }

        /// <summary>
        /// 删除字符串尾部的回车/换行/空格
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RTrim(string str)
        {
            for (int i = str.Length; i >= 0; i--)
            {
                if (str[i].Equals(" ") || str[i].Equals("\r") || str[i].Equals("\n"))
                {
                    str.Remove(i, 1);
                }
            }
            return str;
        }

        /// <summary>
        /// 清除给定字符串中的回车及换行符
        /// </summary>
        /// <param name="str">要清除的字符串</param>
        /// <returns>清除后返回的字符串</returns>
        public static string ClearBR(string str)
        {
            //Regex r = null;
            Match m = null;

            //r = new Regex(@"(\r\n)",RegexOptions.IgnoreCase);
            for (m = RegexBr.Match(str); m.Success; m = m.NextMatch())
            {
                str = str.Replace(m.Groups[0].ToString(), "");
            }
            return str;
        }

        /// <summary>
        /// 从字符串的指定位置截取指定长度的子字符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="startIndex">子字符串的起始位置</param>
        /// <param name="length">子字符串的长度</param>
        /// <returns>子字符串</returns>
        public static string CutString(string str, int startIndex, int length)
        {
            if (startIndex >= 0)
            {
                if (length < 0)
                {
                    length = length * -1;
                    if (startIndex - length < 0)
                    {
                        length = startIndex;
                        startIndex = 0;
                    }
                    else
                    {
                        startIndex = startIndex - length;
                    }
                }

                if (startIndex > str.Length)
                {
                    return "";
                }
            }
            else
            {
                if (length < 0)
                {
                    return "";
                }
                else
                {
                    if (length + startIndex > 0)
                    {
                        length = length + startIndex;
                        startIndex = 0;
                    }
                    else
                    {
                        return "";
                    }
                }
            }

            if (str.Length - startIndex < length)
            {
                length = str.Length - startIndex;
            }

            return str.Substring(startIndex, length);
        }

        /// <summary>
        /// 从字符串的指定位置开始截取到字符串结尾的了符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="startIndex">子字符串的起始位置</param>
        /// <returns>子字符串</returns>
        public static string CutString(string str, int startIndex)
        {
            return CutString(str, startIndex, str.Length);
        }

        /// <summary>
        /// 子字符串从指定的字符位置开始且具有指定的长度
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="length">捷取子字符串的长度</param>
        /// <returns></returns>
        public static string LeftCutString(string str, int length)
        {
            string result = "";

            if (!string.IsNullOrEmpty(str))
            {
                int n = 0;
                for (int i = 0; i < str.Length; i++)
                {
                    string tempstr = str.Substring(i, 1);
                    n += GetStringLength(tempstr);
                    result = result + tempstr;
                    if (n > length + 1) break;
                }
            }

            return result;
        }

        /// <summary>
        /// 分割字符串
        /// </summary>
        public static string[] SplitString(string strContent, string strSplit)
        {
            if (strContent.IndexOf(strSplit) < 0)
            {
                string[] tmp = { strContent };
                return tmp;
            }
            return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <returns></returns>
        public static string[] SplitString(string strContent, string strSplit, int p_3)
        {
            string[] result = new string[p_3];

            string[] splited = SplitString(strContent, strSplit);

            for (int i = 0; i < p_3; i++)
            {
                if (i < splited.Length)
                    result[i] = splited[i];
                else
                    result[i] = string.Empty;
            }

            return result;
        }

        /// <summary>
        /// 删除最后一个字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ClearLastChar(string str)
        {
            if (str == "")
                return "";
            else
                return str.Substring(0, str.Length - 1);
        }

        /// <summary>
        /// 删除段落的首行空格、将br替换成p标记
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ClearStylePSpace(string str)
        {
            if (string.IsNullOrEmpty(str)) return str;
            str = Regex.Replace(str, @"^(\s|&nbsp;)*", @"", RegexOptions.IgnoreCase | RegexOptions.Singleline);    //替换开头的空格字符
            if (!Regex.IsMatch(str, @"^<P.*?>*", RegexOptions.IgnoreCase | RegexOptions.Singleline)) str = "<P>" + str;
            str = Regex.Replace(str, @"<P.*?>(\s|&nbsp;)*", @"<P>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"<br.*?>(\s|&nbsp;)*", @"</P><P>", RegexOptions.IgnoreCase | RegexOptions.Multiline);

            return str;
        }

        public static string ReplaceStylePToBr(string str)
        {
            if (string.IsNullOrEmpty(str)) return str;
            str = Regex.Replace(str, @"</P><P.*?>", @"<br/>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"<P.*?>", @"", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"</P>", @"", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            return str;
        }

        /// <summary>
        /// 将文本框中的字符替换成HTML字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ReplaceTextAreaTextToHTML(string str)
        {
            if (string.IsNullOrEmpty(str)) return str;
            return str.Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace("\r", "<br/>");
        }

        /// <summary>
        /// 将HTML中的字符替换文本框成字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ReplaceHTMLToTextAreaText(string str)
        {
            if (string.IsNullOrEmpty(str)) return str;
            return str.Replace("<br/>", "\r\n");
        }

        /// <summary>
        /// 从HTML中获取文本,保留br,p
        /// </summary>
        /// <param name="HTML"></param>
        /// <returns></returns>
        public static string GetTextFromHTML(string HTML)
        {
            if (string.IsNullOrEmpty(HTML)) return HTML;
            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(@"</?(?!br|/?p)[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regEx1 = new System.Text.RegularExpressions.Regex(@"<p.*?>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            string result = regEx.Replace(HTML, "");
            result = regEx1.Replace(result, "<p>");
            return result.Replace("\"", "'");
        }

        /// <summary>
        /// 返回URL中结尾的文件名
        /// </summary>		
        public static string GetFilename(string url)
        {
            if (url == null)
            {
                return "";
            }
            string[] strs1 = url.Split(new char[] { '/' });
            if (strs1[strs1.Length - 1].Contains("?"))
            {
                return strs1[strs1.Length - 1].Split(new char[] { '?' })[0];
            }
            else
            {
                return strs1[strs1.Length - 1];
            }
        }

        #endregion

        #region 文件操作工具

        /// <summary>
        /// 建立文件夹
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool CreateDir(string name)
        {
            return CommUtils.MakeSureDirectoryPathExists(name);
        }

        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="name">名称</param>
        /// <returns>创建是否成功</returns>
        [DllImport("dbgHelp", SetLastError = true)]
        private static extern bool MakeSureDirectoryPathExists(string name);

        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }

        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="sourceFileName">源文件</param>
        /// <param name="destFileName">目标文件</param>
        /// <param name="destFileDir">目标文件夹</param>
        public static void FileMove(string sourceFileName, string destFileName, string destFileDir,bool isMapPath)
        {
            if (!isMapPath)
            {
                sourceFileName = GetMapPath(@"" + sourceFileName);
                destFileDir = GetMapPath(@"" + destFileDir);
                destFileName = GetMapPath(@"" + destFileName);
            }
            if (FileExists(sourceFileName))
            {
                // 如果指定目录不存在则建立
                if (!Directory.Exists(destFileDir)) Directory.CreateDirectory(destFileDir);
                //移动文件
                if (Directory.Exists(destFileDir)) System.IO.File.Move(sourceFileName, destFileName);
            }
        }

        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="sourceFileName">源文件</param>
        /// <param name="destFileName">目标文件</param>
        /// <param name="destFileDir">目标文件夹</param>
        public static void FileMove(string sourceFileName, string destFileName, string destFileDir)
        {
            if (FileExists(GetMapPath(@"" + sourceFileName)))
            {
                // 如果指定目录不存在则建立
                if (!Directory.Exists(GetMapPath(@"" + destFileDir))) Directory.CreateDirectory(GetMapPath(@"" + destFileDir));
                //移动文件
                if (Directory.Exists(GetMapPath(@"" + destFileDir))) System.IO.File.Move(GetMapPath(@"" + sourceFileName), GetMapPath(@"" + destFileName));
            }
        }

        /// <summary>
        /// 返回文件是否存在
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>是否存在</returns>
        public static bool FileExists(string filename, bool isMapPath)
        {

            bool result = false;
            if (!isMapPath)
            {
                filename = GetMapPath(@"" + filename);
            }
            try
            {
                result = System.IO.File.Exists(filename);
            }
            catch
            {
            }

            return result;
        }

        /// <summary>
        /// 返回文件是否存在
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>是否存在</returns>
        public static bool FileExists(string filename)
        {
            bool result = false;
            try
            {
                result = System.IO.File.Exists(filename);
            }
            catch
            {
            }
            return result;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool DeleteFile(string filename,bool ismappath)
        {
            filename=ismappath?filename:GetMapPath(@"" + filename);
            if (FileExists(filename))
            {
                File.Delete(filename);
                return true;
            }
            return false;
        }


        /// <summary>
        /// 获取文件相关信息
        /// </summary>
        /// <param name="sFullFileName"></param>
        /// <param name="sName"></param>
        /// <param name="sType"></param>
        /// <param name="sSuff"></param>
        public static void GetFileInfo(string sFullFileName, out string sName, out string sType, out string sSuff)
        {
            sName = "";
            sType = "";
            sSuff = "";
            if (!string.IsNullOrEmpty(sFullFileName))
            {
                sName = Path.GetFileNameWithoutExtension(sFullFileName);
                sSuff = Path.GetExtension(sFullFileName).Replace(".", "");
                sType = GetFileType(sSuff);
            }
        }

        public static string GetFileType(string sFileExtension)
        {
            sFileExtension = sFileExtension.ToLower();
            switch (sFileExtension)
            {
                case "doc":
                    return "Word";
                case "docx":
                    return "Word";
                case "docm":
                    return "Word";
                case "dot":
                    return "Word";
                case "dotm":
                    return "Word";
                case "xls":
                    return "Excel";
                case "xlsx":
                    return "Excel";
                case "xlsm":
                    return "Excel";
                case "xltx":
                    return "Excel";
                case "xltm":
                    return "Excel";
                case "xlsb":
                    return "Excel";
                case "xlam":
                    return "Excel";
                case "ppt":
                    return "PPT";
                case "pptx":
                    return "PPT";
                case "pptm":
                    return "PPT";
                case "ppsx":
                    return "PPT";
                case "potx":
                    return "PPT";
                case "potm":
                    return "PPT";
                case "ppam":
                    return "PPT";
                case "xml":
                    return "Xml";
                case "txt":
                    return "Txt";
                case "pdf":
                    return "PDF";
                default:
                    return sFileExtension.ToUpper();
            }
        }

        #endregion

        #region 加密工具

        /// <summary>
        /// MD5函数
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <returns>MD5结果</returns>
        public static string MD5(string str)
        {
            byte[] b = Encoding.Default.GetBytes(str);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("x").PadLeft(2, '0');
            return ret;
        }

        /// <summary>
        /// SHA256函数
        /// </summary>
        /// /// <param name="str">原始字符串</param>
        /// <returns>SHA256结果</returns>
        public static string SHA256(string str)
        {
            byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
            SHA256Managed Sha256 = new SHA256Managed();
            byte[] Result = Sha256.ComputeHash(SHA256Data);
            return Convert.ToBase64String(Result);  //返回长度为44字节的字符串
        }

        const string KEY_64 = "MyWorldA";//注意了，是8个字符，64位
        const string IV_64 = "MyWorldA";

        /// <summary>
        /// MDB可逆加密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Encode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

        }

        /// <summary>
        /// MD5逆解密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Decode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }

        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Base64Encode(string str)
        {
            Encoding ens = Encoding.GetEncoding(54936);
            return Convert.ToBase64String(ens.GetBytes(str));
        }

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Base64Decode(string str)
        {
            Encoding ens = Encoding.GetEncoding(54936);
            return ens.GetString(Convert.FromBase64String(str));
        }

        #endregion

        #region 格式及类型检测、替换工具

        /// <summary>
        /// 检测是否符合email格式
        /// </summary>
        /// <param name="strEmail">要判断的email字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsValidEmail(string strEmail)
        {
            return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        /// <summary>
        /// 是否为ip
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        /// <summary>
        /// 判断对象是否为Int32类型的数字
        /// </summary>
        /// <param name="Expression"></param>
        /// <returns></returns>
        public static bool IsNumeric(object Expression)
        {
            return TypeParse.IsNumeric(Expression);
        }

        /// <summary>
        /// 验证是否为正整数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsInt(string str)
        {
            return Regex.IsMatch(str, @"^[0-9]*$");
        }

        /// <summary>
        /// 判断对象是否为字母
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsLetters(string str)
        {
            Regex reg1 = new Regex(@"^[A-Za-z]+$");
            return reg1.IsMatch(str);
        }

        /// <summary>
        /// 检测是否是正确的Url
        /// </summary>
        /// <param name="strUrl">要验证的Url</param>
        /// <returns>判断结果</returns>
        public static bool IsURL(string strUrl)
        {
            return Regex.IsMatch(strUrl, @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
        }

        /// <summary>
        /// 检测是否有Sql危险字符
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsSafeSqlString(string str)
        {
            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|\%|\@|\*|\!|\'|\""]");
        }

        /// <summary>
        /// 将sql危险字符替换为空
        /// </summary>
        /// <returns></returns>
        public static string ReplaceSafeSqlString(string str)
        {
            return Regex.Replace(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|\%|\@|\*|!|\'|\""]", "", RegexOptions.Compiled | RegexOptions.Multiline);
        }

        /// <summary>
        /// 清除超链接
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ClearLinkHtml(string str)
        {
            str = Regex.Replace(str, @"(<a\s.*?>)", "", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"(<\/a>)", "", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            return str;
        }

        /// <summary>
        /// 移除Html标记
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveHtml(string content)
        {
            string regexstr = @"<[^>]*>";
            return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 过滤HTML中的不安全标签
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveUnsafeHtml(string content)
        {
            content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
            content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
            return content;
        }

        /// <summary>
        /// 判断文件名是否为浏览器可以直接显示的图片文件名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>是否可以直接显示</returns>
        public static bool IsImgFilename(string filename)
        {
            filename = filename.Trim();
            if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
            {
                return false;
            }
            string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
            return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
        }

        #endregion

        #region URL相关工具

        /// <summary>
        /// 获取所有参数中的值，连成一个字符串
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetUrlParameterValueAll(string url)
        {
            string result = "";
            if (url.IndexOf("?") > -1)
            {
                url = url.Replace(url.Substring(0, url.IndexOf("?")) + "?", "");
            }
            url += "&";
            string[] splitUrl = CommUtils.SplitString(url, "&");
            for (int i = 0; i < splitUrl.Length; i++)
            {
                if (string.IsNullOrEmpty(splitUrl[i])) continue;
                if (splitUrl[i].IndexOf("=") <= 0) continue;
                string[] splitUrl2 = CommUtils.SplitString(splitUrl[i], "=");
                result += splitUrl2[1];
            }
            return result;
        }

        /// <summary>
        /// 返回URL地址中参数的值
        /// </summary>
        /// <param name="url"></param>
        /// <param name="delParameter"></param>
        /// <returns></returns>
        public static string GetUrlParameterValue(string url, string parameter)
        {
            string result = "";
            if (url.IndexOf("?") > -1)
            {
                url = url.Replace(url.Substring(0, url.IndexOf("?")) + "?", "");
            }
            url += "&";
            string[] splitUrl = CommUtils.SplitString(url, "&");
            for (int i = 0; i < splitUrl.Length; i++)
            {
                if (string.IsNullOrEmpty(splitUrl[i])) continue;
                if (splitUrl[i].IndexOf("=") <= 0) continue;
                if (splitUrl[i].Substring(0, splitUrl[i].IndexOf("=")).ToLower() == parameter.ToLower())
                {
                    result = splitUrl[i].Replace(parameter + "=", "");
                    if (result.IndexOf("#") > -1) result = result.Substring(0, result.IndexOf("#"));
                }
            }
            return result;
        }

        /// <summary>
        /// 删除URL地址中的参数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="delParameter"></param>
        /// <returns></returns>
        public static string DelUrlParameter(string url, string delParameter)
        {
            string result = "";

            if (url.IndexOf("?") > -1)
            {
                result = url.Substring(0, url.IndexOf("?")) + "?";
                url = url.Replace(result, "");
            }

            url += "&";
            string[] splitUrl = CommUtils.SplitString(url, "&");

            for (int i = 0; i < splitUrl.Length; i++)
            {
                if (string.IsNullOrEmpty(splitUrl[i])) continue;
                if (splitUrl[i].IndexOf("=") <= 0) continue;
                if (splitUrl[i].Substring(0, splitUrl[i].IndexOf("=")).ToLower() != delParameter.ToLower())
                {
                    result += splitUrl[i].ToString() + "&";
                }
            }

            return result;
        }

        /// <summary>
        /// URL地址重写（伪静态）
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string URLRewriteStr(string url)
        {
            StringBuilder result = new StringBuilder("");

            string lowerUrl = url.ToLower();
            if (lowerUrl.IndexOf("/booksearch.aspx") > -1)
            {
                result.Append("/book/");
                if (lowerUrl.IndexOf("categoryid=") > -1)
                {
                    result.Append(CommUtils.GetUrlParameterValue(url, "CategoryID"));
                    result.Append("/");
                }
                else if (lowerUrl.IndexOf("letterindex=") > -1)
                {
                    result.Append(CommUtils.GetUrlParameterValue(url, "LetterIndex"));
                    result.Append("/");
                }

                if (lowerUrl.IndexOf("orderby=") > -1 ||
                    lowerUrl.IndexOf("style=") > -1 ||
                    lowerUrl.IndexOf("page=") > -1 ||
                    lowerUrl.IndexOf("searchtype=") > -1 ||
                    lowerUrl.IndexOf("searchkey=") > -1)
                {
                    result.Append(CommUtils.GetUrlParameterValue(url, "OrderBy"));
                    result.Append("-");
                    result.Append(CommUtils.GetUrlParameterValue(url, "Style"));
                    result.Append("-");
                    result.Append(CommUtils.GetUrlParameterValue(url, "page"));
                    result.Append("-");
                    result.Append(CommUtils.GetUrlParameterValue(url, "SearchType"));
                    result.Append("-");
                    result.Append(CommUtils.GetUrlParameterValue(url, "SearchKey"));
                    result.Append("-0");
                }
            }

            if (lowerUrl.IndexOf("/bookmain.aspx") > -1)
            {
                result.Append("/book/index");
                result.Append(CommUtils.GetUrlParameterValue(url, "ListType"));
                result.Append("-");
                result.Append(CommUtils.GetUrlParameterValue(url, "page"));
                result.Append("-");
                result.Append(CommUtils.GetUrlParameterValue(url, "BookID"));
                result.Append(".html");
                if (lowerUrl.IndexOf("#") > -1)
                {
                    result.Append(lowerUrl.Substring(lowerUrl.IndexOf("#"), lowerUrl.Length - lowerUrl.IndexOf("#")));
                }
            }

            if (lowerUrl.IndexOf("/bookread.aspx") > -1)
            {
                result.Append("/book/");
                result.Append(CommUtils.GetUrlParameterValue(url, "BookID"));
                result.Append("/");
                result.Append("view-");
                result.Append(CommUtils.GetUrlParameterValue(url, "ChapterID"));
                result.Append(".html");
            }

            if (lowerUrl.IndexOf("/user_view.aspx") > -1)
            {
                result.Append("/user/view-");
                result.Append(CommUtils.GetUrlParameterValue(url, "ViewType"));
                result.Append("-");
                result.Append(CommUtils.GetUrlParameterValue(url, "ViewUserID"));
                result.Append(".html");
            }

            if (result.Length == 0) result.Append(url);

            return result.ToString();
        }

        #endregion

        #region 翻页与页码

        /// <summary>
        /// 获得页码显示链接
        /// </summary>
        /// <param name="recordCount">总记录数</param>
        /// <param name="curPage">当前页数</param>
        /// <param name="countPage">总页数</param>
        /// <param name="url">超级链接地址</param>
        /// <param name="extendPage">周边页码显示个数上限</param>
        /// <returns>页码html</returns>
        public static string GetPageNumbers(int countRecord, int curPage, int countPage, string url, int extendPage)
        {
            return GetPageNumbers(countRecord, curPage, countPage, url, extendPage, "page");
        }

        /// <summary>
        /// 获得页码显示链接
        /// </summary>
        /// <param name="recordCount">总记录数</param>
        /// <param name="curPage">当前页数</param>
        /// <param name="countPage">总页数</param>
        /// <param name="url">超级链接地址</param>
        /// <param name="extendPage">周边页码显示个数上限</param>
        /// <param name="pagetag">页码标记</param>
        /// <returns>页码html</returns>
        public static string GetPageNumbers(int countRecord, int curPage, int countPage, string url, int extendPage, string pagetag)
        {
            string prepage1 = " <img src='/images/btn_pre.gif' border='0' align='absmiddle'> ";//有连接
            string nextpage1 = " <img src='/images/btn_next.gif' border='0' align='absmiddle'> ";//有连接
            string prepage2 = " <img src='/images/btn_pre2.gif' border='0' align='absmiddle'> ";//无连接
            string nextpage2 = " <img src='/images/btn_next2.gif' border='0' align='absmiddle'> ";//无连接

            if (pagetag == "") pagetag = "page";

            if (curPage < 1) curPage = 1;
            if (curPage > countPage) curPage = countPage;

            int startPage = 1;
            int endPage = 1;

            if (countPage < 1) countPage = 1;
            if (extendPage < 3) extendPage = 2;

            if (countPage > extendPage)
            {
                if (curPage - (extendPage / 2) > 0)
                {
                    if (curPage + (extendPage / 2) < countPage)
                    {
                        startPage = curPage - (extendPage / 2);
                        endPage = startPage + extendPage - 1;
                    }
                    else
                    {
                        endPage = countPage;
                        startPage = endPage - extendPage + 1;
                    }
                }
                else
                {
                    endPage = extendPage;
                }
            }
            else
            {
                startPage = 1;
                endPage = countPage;
            }

            StringBuilder s = new StringBuilder("");

            s.Append(" 共" + countRecord + "条 共" + countPage + "页 ");

            if (curPage > 1)
            {
                s.Append(" <a href=\"" + CommUtils.URLRewriteStr(url + pagetag + "=" + (curPage - 1)) + "\">" + prepage1 + "</a> ");
            }
            else
            {
                s.Append(prepage2);
            }

            for (int i = startPage; i <= endPage; i++)
            {
                if (i == curPage)
                {
                    s.Append("<span class='pageLinkA'>");
                    s.Append(i);
                    s.Append("</span>");
                }
                else
                {
                    s.Append("<a href=\"" + CommUtils.URLRewriteStr(url + pagetag + "=" + i) + "\" class=\"pageLinkN\">" + i + "</a>");
                }
            }

            if (curPage < countPage)
            {
                s.Append(" <a href=\"" + CommUtils.URLRewriteStr(url + pagetag + "=" + (curPage + 1)) + "\">" + nextpage1 + "</a> ");
            }
            else
            {
                s.Append(nextpage2);
            }

            s.Append(" 转<input type='text' title='输入页码后回车' maxlength='4' style='width:25px; height:18px; line-height:18px; font-size:12px;' value='" + curPage + "' onkeydown=\"if(event.keyCode==13){event.keyCode=9;window.location.href='" + CommUtils.URLRewriteStr(url + "" + pagetag + "='+this.value+'") + "';}\">页");

            return s.ToString();
        }

        public static string GetPageHTML(string url, int pageSize, int pageIndex, int count)
        {
            return GetPageHTML(url, pageSize, pageIndex, count, 8);
        }

        public static string GetPageHTML(string url, int pageSize, int pageIndex, int count, int extendPage)
        {
            //求出总页数
            int pageNum = 0;
            if (count % pageSize == 0)
            {
                pageNum = count / pageSize;
            }
            else
            {
                pageNum = (count / pageSize) + 1;
            }
            if (pageIndex > pageNum) pageIndex = pageNum;
            //生成页码
            string pageNumbers = "";
            string pageNumbersUrl = CommUtils.DelUrlParameter(url, "page");
            pageNumbers = CommUtils.GetPageNumbers(count, pageIndex, pageNum, pageNumbersUrl, extendPage);
            return pageNumbers;
        }

        #endregion

        #region 编码与解码

        /// <summary>
        /// 返回 HTML 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string HtmlEncode(string str)
        {
            return HttpUtility.HtmlEncode(str);
        }

        /// <summary>
        /// 返回 HTML 字符串的解码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string HtmlDecode(string str)
        {
            return HttpUtility.HtmlDecode(str);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string UrlEncode(string str)
        {
            return HttpUtility.UrlEncode(str);
            //return HttpUtility.UrlEncode(str, System.Text.Encoding.GetEncoding("GB2312"));
        }

        /// <summary>
        /// 返回 URL 字符串的解码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string UrlDecode(string str)
        {
            return HttpUtility.UrlDecode(str);
            //return HttpUtility.UrlDecode(str, System.Text.Encoding.GetEncoding("GB2312"));
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string UrlEncode(string str, string charset)
        {
            return HttpUtility.UrlEncode(str, System.Text.Encoding.GetEncoding(charset));
        }

        /// <summary>
        /// 返回 URL 字符串的解码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string UrlDecode(string str, string charset)
        {
            return HttpUtility.UrlDecode(str, System.Text.Encoding.GetEncoding(charset));
        }

        #endregion

        #region cookie操作

        /// <summary>
        /// 检测COOKIE
        /// </summary>
        /// <returns></returns>
        public static bool CheckCookieState()
        {
            if (string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_COOKIE"]))
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        public static void WriteCookie(string strName, string strValue)
        {
            WriteCookie(strName, strValue, "", "");
        }

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="domain">域</param>
        /// <param name="path">路径</param>
        public static void WriteCookie(string strName, string strValue, string domain, string path)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            if (!string.IsNullOrEmpty(path)) cookie.Path = path;
            if (!string.IsNullOrEmpty(domain)) cookie.Domain = domain;
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="strValue">过期时间(分钟)</param>
        public static void WriteCookie(string strName, string strValue, int expires)
        {
            WriteCookie(strName, strValue, expires, "", "/");
        }

        /// <summary>
        /// /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="expires">过期时间(分钟)</param>
        /// <param name="domain">域</param>
        /// <param name="path">路径</param>
        public static void WriteCookie(string strName, string strValue, int expires, string domain, string path)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            cookie.Expires = DateTime.Now.AddMinutes(expires);
            if (!string.IsNullOrEmpty(path)) cookie.Path = path;
            if (!string.IsNullOrEmpty(domain)) cookie.Domain = domain;
            HttpContext.Current.Response.AppendCookie(cookie);

        }

        /// <summary>
        /// 读cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <returns>cookie值</returns>
        public static string GetCookie(string strName)
        {
            try
            {
                if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
                {
                    return HttpContext.Current.Request.Cookies[strName].Value.ToString();
                }
            }
            catch
            {
            }

            return "";
        }

        #endregion

        #region 数据类型转换

        /// <summary>
        /// string型转换为bool型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的bool类型结果</returns>
        public static bool StrToBool(object Expression, bool defValue)
        {
            return TypeParse.StrToBool(Expression, defValue);
        }

        /// <summary>
        /// 将对象转换为Int32类型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static int StrToInt(object Expression, int defValue)
        {
            return TypeParse.StrToInt(Expression, defValue);
        }

        /// <summary>
        /// string型转换为float型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static float StrToFloat(object strValue, float defValue)
        {
            return TypeParse.StrToFloat(strValue, defValue);
        }

        #endregion

        #region 时间格式

        /// <summary>
        /// 返回标准日期格式string yyyy-MM-dd
        /// </summary>
        public static string GetDate()
        {
            return DateTime.Now.ToString("yyyy-MM-dd");
        }

        /// <summary>
        /// 返回标准时间格式string HH:mm:ss
        /// </summary>
        public static string GetTime()
        {
            return DateTime.Now.ToString("HH:mm:ss");
        }

        /// <summary>
        /// 返回标准时间格式string yyyy-MM-dd HH:mm:ss
        /// </summary>
        public static string GetDateTime()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        /// <summary>
        /// 返回标准日期格式string yyyy-MM-dd
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string GetDate(DateTime dt)
        {
            return dt.ToString("yyyy-MM-dd");
        }

        /// <summary>
        /// 返回标准日期格式 如：2005年11月5日 
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string GetChDate(DateTime dt)
        {
            return dt.ToLongDateString();
        }

        #endregion

        #region 提取汉字的首字母

        /// <summary>
        /// 返回给定字符串的单个字母
        /// </summary>
        /// <param name="IndexTxt"></param>
        /// <returns></returns>
        public static String IndexCode(String IndexTxt)
        {
            String _Temp = null;
            for (int i = 0; i < IndexTxt.Length; i++)
                _Temp = _Temp + GetOneIndex(IndexTxt.Substring(i, 1));
            return _Temp;
        }

        /// <summary>
        /// 得到单个字符的首字母
        /// </summary>
        /// <param name="OneIndexTxt"></param>
        /// <returns></returns>
        private static String GetOneIndex(String OneIndexTxt)
        {
            if (Convert.ToChar(OneIndexTxt) >= 0 && Convert.ToChar(OneIndexTxt) < 256)
                return OneIndexTxt;
            else
                return GetGbkX(OneIndexTxt);
        }

        /// <summary>
        ///根据根据测字拼音排序得到首字母
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string GetGbkX(string str)
        {
            if (str.CompareTo("吖") < 0)
            {
                return str;
            }
            if (str.CompareTo("八") < 0)
            {
                return "A";
            }
            if (str.CompareTo("嚓") < 0)
            {
                return "B";
            }
            if (str.CompareTo("咑") < 0)
            {
                return "C";
            }
            if (str.CompareTo("妸") < 0)
            {
                return "D";
            }
            if (str.CompareTo("发") < 0)
            {
                return "E";
            }
            if (str.CompareTo("旮") < 0)
            {
                return "F";
            }
            if (str.CompareTo("铪") < 0)
            {
                return "G";
            }
            if (str.CompareTo("讥") < 0)
            {
                return "H";
            }
            if (str.CompareTo("咔") < 0)
            {
                return "J";
            }
            if (str.CompareTo("垃") < 0)
            {
                return "K";
            }
            if (str.CompareTo("嘸") < 0)
            {
                return "L";
            }
            if (str.CompareTo("拏") < 0)
            {
                return "M";
            }
            if (str.CompareTo("噢") < 0)
            {
                return "N";
            }
            if (str.CompareTo("妑") < 0)
            {
                return "O";
            }
            if (str.CompareTo("七") < 0)
            {
                return "P";
            }
            if (str.CompareTo("亽") < 0)
            {
                return "Q";
            }
            if (str.CompareTo("仨") < 0)
            {
                return "R";
            }
            if (str.CompareTo("他") < 0)
            {
                return "S";
            }
            if (str.CompareTo("哇") < 0)
            {
                return "T";
            }
            if (str.CompareTo("夕") < 0)
            {
                return "W";
            }
            if (str.CompareTo("丫") < 0)
            {
                return "X";
            }
            if (str.CompareTo("帀") < 0)
            {
                return "Y";
            }
            if (str.CompareTo("咗") < 0)
            {
                return "Z";
            }
            return str;
        }

        #endregion

        #region 邮箱验证
        /// <summary>
        /// 验证字符串是正确的电子邮箱格式,包含特殊字符的验证
        /// </summary>
        /// <param name="strIn"></param>
        /// <returns></returns>
        public static bool IsMailString(string strIn)
        {
            return Regex.IsMatch(strIn, @"^\s*([A-Za-z0-9_-]+(\.\w+)*@([\w-]+\.)+\w{2,3})\s*$");
        }
        #endregion

        #region 将阿拉伯数字转换成汉字

        /// <summary>
        ///转换数字
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static char ChangeCharNumber(char x)
        {
            string stringChnNames = "零一二三四五六七八九";
            string stringNumNames = "0123456789";
            return stringChnNames[stringNumNames.IndexOf(x)];
        }

        /// <summary>
        ///转换万以下整数
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string ChangeTopWanNumber(string x)
        {
            string[] stringArrayLevelNames = new string[4] { "", "十", "百", "千" };
            string ret = "";
            int i;
            for (i = x.Length - 1; i >= 0; i--)
                if (x[i] == '0')
                    ret = ChangeCharNumber(x[i]) + ret;
                else
                    ret = ChangeCharNumber(x[i]) + stringArrayLevelNames[x.Length - 1 - i] + ret;
            while ((i = ret.IndexOf("零零")) != -1)
                ret = ret.Remove(i, 1);
            if (ret[ret.Length - 1] == '零' && ret.Length > 1)
                ret = ret.Remove(ret.Length - 1, 1);
            if (ret.Length >= 2 && ret.Substring(0, 2) == "一十")
                ret = ret.Remove(0, 1);
            return ret;
        }

        /// <summary>
        ///转换整数
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string ChangeNumber(string x)
        {
            int len = x.Length;
            string ret, temp;
            if (len <= 4)
                ret = ChangeTopWanNumber(x);
            else if (len <= 8)
            {
                ret = ChangeTopWanNumber(x.Substring(0, len - 4)) + "万";
                temp = ChangeTopWanNumber(x.Substring(len - 4, 4));
                if (temp.IndexOf("千") == -1 && temp != "")
                    ret += "零" + temp;
                else
                    ret += temp;
            }
            else
            {
                ret = ChangeTopWanNumber(x.Substring(0, len - 8)) + "亿";
                temp = ChangeTopWanNumber(x.Substring(len - 8, 4));
                if (temp.IndexOf("千") == -1 && temp != "")
                    ret += "零" + temp;
                else
                    ret += temp;
                ret += "万";
                temp = ChangeTopWanNumber(x.Substring(len - 4, 4));
                if (temp.IndexOf("千") == -1 && temp != "")
                    ret += "零" + temp;
                else
                    ret += temp;
            }
            int i;
            if ((i = ret.IndexOf("零万")) != -1)
                ret = ret.Remove(i + 1, 1);
            while ((i = ret.IndexOf("零零")) != -1)
                ret = ret.Remove(i, 1);
            if (ret[ret.Length - 1] == '零' && ret.Length > 1)
                ret = ret.Remove(ret.Length - 1, 1);
            return ret;
        }

        /// <summary>
        ///转换小数 
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string ChangeFloatNumber(string x)
        {
            string ret = "";
            for (int i = 0; i < x.Length; i++)
                ret += ChangeCharNumber(x[i]);
            return ret;
        }

        /// <summary>
        ///将阿拉伯数字转换成汉字
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string NumToChn(string x)
        {
            if (x.Length == 0)
                return "";
            string ret = "";
            if (x[0] == '-')
            {
                ret = "负";
                x = x.Remove(0, 1);
            }
            if (x[0].ToString() == ".")
                x = "0" + x;
            if (x[x.Length - 1].ToString() == ".")
                x = x.Remove(x.Length - 1, 1);
            if (x.IndexOf(".") > -1)
                ret += ChangeNumber(x.Substring(0, x.IndexOf("."))) + "点" + ChangeFloatNumber(x.Substring(x.IndexOf(".") + 1));
            else
                ret += ChangeNumber(x);
            return ret;
        }
        #endregion
    }
}
